﻿using System;
using System.Configuration;
using System.Threading;
using Autofac;
using Moq;
using Wombat.Core.EventAggregator;
using Wombat.Data;
using Wombat.DbToDwAdapter;

namespace Wombat.Db2DwSync
{
    class Program
    {
        static void Main()
        {
            var container = Bootstrap();

            var eventPub = container.Resolve<IEventPublisher>();
            var sync = container.Resolve<SyncToDw>();

            eventPub.GetEvent<DataMigrationEvent>()
                    .Subscribe(e => Console.WriteLine(e.Status));

            Console.WriteLine(@"Starting synchronization...");
            var wait = true;
            sync.Synchronize()
                .ContinueWith(t =>
                    {
                        wait = false;
                        if (t.IsFaulted) Faulted(t.Exception);
                        else
                            Console.WriteLine(@"@Synchronization completed successfully.");
                    });

            while (wait)
            {
                Thread.Sleep(1000);
            }
            Console.ReadLine();
        }

        private static void Faulted(AggregateException exception)
        {
            Console.WriteLine(exception);
        }

        private static IContainer Bootstrap()
        {
            var builder = new ContainerBuilder();

            builder.RegisterType<FactInterpolationService>()
                   .As<IFactAggregationService>();

            builder.RegisterType<SyncToDwOrchestrator>()
                   .As<IOrchestrator>();

            builder.RegisterType<SqlDal>()
                   .As<IDal>();

            builder.RegisterType<BasicTempFileService>()
                   .As<ITempFileService>();

            builder.Register(c =>
                             new SyncToDw(c.Resolve<IOrchestrator>(),
                                          new DataSourceFactory().Create(
                                              ConfigurationManager.AppSettings["SourceConnectionString"]),
                                          new DataSourceFactory().Create(
                                              ConfigurationManager.AppSettings["DestinationConnectionString"])
                                 ));

            builder.RegisterType<EventPublisher>()
                   .As<IEventPublisher>()
                   .SingleInstance();

            var container = builder.Build();
            return container;
        }
    }
}
